package com.atguigu.dga.governance.assessor.calc;


import com.atguigu.dga.common.utils.SqlParser;
import com.atguigu.dga.ds.bean.TDsTaskDefinition;
import com.atguigu.dga.governance.assessor.Assessor;
import com.atguigu.dga.governance.bean.AssessParam;
import com.atguigu.dga.governance.bean.GovernanceAssessDetail;

import org.apache.hadoop.hive.ql.lib.Dispatcher;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.parse.ASTNode;
import org.apache.hadoop.hive.ql.parse.HiveParser;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Stack;

@Component("IS_SELECT_ALL")
public class IsSelectAllAssessor extends Assessor {
    @Override
    public void checkProblem(AssessParam assessParam, GovernanceAssessDetail governanceAssessDetail) throws ParseException {
        TDsTaskDefinition tDsTaskDefinition = assessParam.getTDsTaskDefinition();
        if(tDsTaskDefinition==null){
            return;
        }
        String sql = tDsTaskDefinition.getSql();
        CheckSelectAllDispatcher checkSelectAllDispatcher=new CheckSelectAllDispatcher();
        try {
            SqlParser.parseSQL(sql, checkSelectAllDispatcher );
        } catch (Exception e) {
            throw new RuntimeException("sql 解析异常");
        }
        boolean isSelectAll = checkSelectAllDispatcher.isSelectAll;
        if (isSelectAll){
            governanceAssessDetail.setAssessScore(BigDecimal.ZERO);
            governanceAssessDetail.setAssessProblem("包含 select * ");
        }

    }

    class  CheckSelectAllDispatcher implements Dispatcher {
        boolean isSelectAll = false;

        @Override
        public Object dispatch(Node nd, Stack<Node> stack, Object... nodeOutputs) throws SemanticException {
            ASTNode astNode = (ASTNode) nd;
            if(astNode.getType()== HiveParser.TOK_ALLCOLREF){
                isSelectAll = true;
            }
            return null;
        }
    }
}
